/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-07-23 16:30:58
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-08-16 16:03:28
 * @FilePath: /vue3-uniapp/src/plugins/hook.ts
 */
import { Subject } from 'rxjs';

import { useUserStore } from '@/store';
import { useNotifySubject } from '@/service/app/useNotifySubject';
import { notifyAfterAtuh } from '@/service/hook/useAfterAuth';

type AuthType = 'token' | 'login';

const authSubject = new Subject<AuthType>();
const auth$ = authSubject.pipe();

export const notifyAuthChange = (type: AuthType) => {
    authSubject.next(type);
};

export const setupHook: SetupFunc = () => {
    const userStore = useUserStore();
    const { userInfo, token, hasVaildToken } = storeToRefs(userStore);
    const { info } = useNotifySubject();

    const handleAuth = async () => {
        try {
            await userStore.getUserInfo();
            hasVaildToken.value = true;
            if (
                userInfo.value?.roleList &&
                userInfo.value.roleList.length > 0
            ) {
                notifyAfterAtuh(true);
            } else {
                info({
                    msg: '当前账号无角色，请等待管理员分配角色哦'
                });
            }
            // uni.getLocation({
            //     type: 'wgs84',
            //     success: function(res) {
            //         console.log('获取位置信息');
            //         getGps({
            //             'latitude': res.latitude,
            //             'longitude': res.longitude
            //         })
            //         setGps();
            //     }
            // })
            // RequestManager.setAll(myTodo);
            // setNoticeTimer();
            // checkPrivacySetting();
        } catch (e) {
            hasVaildToken.value = false;
            console.log(e);
        }
    };

    if (token) {
        handleAuth();
        notifyAuthChange('token');
    } else {
        hasVaildToken.value = false;
    }

    auth$.subscribe({
        next: (type) => {
            console.log(`[./plugins/hook]${type}验权`);
            handleAuth();
        }
    });
};
